Imports System.Net
Imports System.IO
Imports System.Text

Friend Class RenderosityDownloader
    Inherits BaseDownloader

    Friend Const BASE_PAGE_URL As String = "http://market.renderosity.com/mod/bcs/index.php?ViewProduct={0}"
    Private Const IMAGE_URL As String = "http://market.renderosity.com/mod/bcs/photos/Full{0}.jpg"
    Private Const IMAGE_URL2 As String = "http://market.renderosity.com/mod/bcs/photos/{0}"
    Private Const READ_ME_URL As String = "http://www.renderosity.com/mod/bcs/index.php?DownloadHelpFile={0}"

    Private Const URL_TO_REMOVE As String = "http://market.renderosity.com/mod/bcs/index.php?ViewProduct="

    Private Const IMAGE_URL_START_MATCH As String = "</H3><IMG SRC=""photos/"
    Private Const IMAGE_URL_END_MATCH As String = """><BR><BR>"

    Private Const PRODUCT_NAME_START_MATCH As String = "<H3>"
    Private Const PRODUCT_NAME_END_MATCH As String = "</H3>"

    Private Const PRICE_START_MATCH As String = "<td align=""right"">List Price:</td><td style=""font-weight:bold;"">$"
    Private Const PRICE_END_MATCH As String = "</td></tr>"

    Private Const STRIKE_START As String = "<strike>"
    Private Const STRIKE_END As String = "</strike>"

    Private Const REQUIREMENTS_START_MATCH As String = "Product Requirements:</b>"
    Private Const REQUIREMENTS_END_MATCH As String = "<p>"

    Private Const ARTIST_START_MATCH As String = "<a href=""index.php?vendor="
    Private Const ARTIST_END_MATCH As String = """>"

    Public Const SEPARATOR As String = ", "

    Public Const LINK_FILENAME As String = "RenderosityLinks.xml"

    Public Overrides ReadOnly Property BasePageUrl() As String
        Get
            Return BASE_PAGE_URL
        End Get
    End Property

    Public Overrides ReadOnly Property BaseImageUrl() As String
        Get
            Return IMAGE_URL2
        End Get
    End Property

    Public Overrides ReadOnly Property LinkFilename() As String
        Get
            Return LINK_FILENAME
        End Get
    End Property

    Public Overrides ReadOnly Property UrlToRemove() As String
        Get
            Return URL_TO_REMOVE
        End Get
    End Property

    Public Sub New(ByVal imageDirectory As String, _
                   ByVal imageHolder As PictureBox)
        MyBase.New(imageDirectory, _
                    imageHolder)
    End Sub

    Private Function GetProductName(ByVal pageContents As String) As String

        Dim productCodeStart As Integer = pageContents.IndexOf(PRODUCT_NAME_START_MATCH)
        Dim productName As String = ""

        If productCodeStart > -1 Then
            pageContents = pageContents.Substring(productCodeStart)
            pageContents = pageContents.Substring(0, pageContents.IndexOf(PRODUCT_NAME_END_MATCH))
            pageContents = pageContents.Replace(PRODUCT_NAME_START_MATCH, EMPTY)
            productName = pageContents.Trim
        End If

        Return productName

    End Function

    Private Function GetPrice(ByVal pageContents As String) As Single

        Dim productCodeStart As Integer = pageContents.IndexOf(PRICE_START_MATCH)
        Dim price As Single = 0.0

        If productCodeStart > -1 Then
            pageContents = pageContents.Substring(productCodeStart)
            pageContents = pageContents.Substring(0, pageContents.IndexOf(PRICE_END_MATCH))
            pageContents = pageContents.Replace(PRICE_START_MATCH, EMPTY)
            pageContents = pageContents.Replace(STRIKE_START, EMPTY)
            pageContents = pageContents.Replace(STRIKE_END, EMPTY)
            Try
                price = CType(pageContents, Single)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        End If

        Return price

    End Function

    Private Function GetRequiredProducts(ByVal pageContents As String) As String

        Dim requiredProducts As String = ""
        Dim requiredProductTemp As String = ""

        Dim requiredProductsStart As Integer = pageContents.IndexOf(REQUIREMENTS_START_MATCH)

        If requiredProductsStart > -1 Then
            pageContents = pageContents.Substring(requiredProductsStart)
            pageContents = pageContents.Substring(0, pageContents.IndexOf(REQUIREMENTS_END_MATCH))
            pageContents = pageContents.Replace(REQUIREMENTS_START_MATCH, EMPTY)
        End If

        Return requiredProducts

    End Function

    Private Function GetArtists(ByVal pageContents As String) As String

        Dim artists As String = ""
        Dim artistsTemp As String = ""

        Dim artistsStart As Integer = pageContents.IndexOf(ARTIST_START_MATCH)

        'If artistsStart > -1 Then

        
        While artistsStart > -1
            pageContents = pageContents.Substring(artistsStart)
            artistsTemp = pageContents.Substring(0, pageContents.IndexOf(ARTIST_END_MATCH))
            artistsTemp = artistsTemp.Replace(ARTIST_START_MATCH, EMPTY)
            If artists.Length > 0 Then
                artists &= SEPARATOR
            End If
            artists &= artistsTemp
            pageContents = pageContents.Replace(ARTIST_START_MATCH & artistsTemp, EMPTY)
            artistsStart = pageContents.IndexOf(ARTIST_START_MATCH)
        End While

        Return artists

    End Function


    Public Overrides Function DownloadImage(ByVal productCode As String, _
                                            ByVal productUrl As String) As String

        Dim productId As Integer = 0
        Try
            productId = CType(productUrl.Replace(URL_TO_REMOVE, EMPTY), Integer)
        Catch ex As Exception
            Throw New InvalidProductUrlException
        End Try

        Dim pageContents As String = GetPageContents(productId)
        Dim imageNameStart As Integer = pageContents.IndexOf(IMAGE_URL_START_MATCH)
        If imageNameStart > -1 Then
            pageContents = pageContents.Substring(imageNameStart)
            pageContents = pageContents.Substring(0, pageContents.IndexOf(IMAGE_URL_END_MATCH))
            pageContents = pageContents.Replace(IMAGE_URL_START_MATCH, EMPTY)
            pageContents = pageContents.Trim
            Try
                Dim fileName As String = My.Settings.ImageDirectory
                fileName &= productCode
                fileName &= JPEG_EXTENSION

                _imageHolder.Load(String.Format(BaseImageUrl, pageContents))
                _imageHolder.Image.Save(fileName, _
                                        System.Drawing.Imaging.ImageFormat.Jpeg)
                Application.DoEvents()
            Catch ex As System.Net.WebException
                If ex.Status <> WebExceptionStatus.ProtocolError Then
                    MsgBox(ex.Message)
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally

            End Try
        End If

        Return productCode & JPEG_EXTENSION

    End Function

    Public Shared Function GetReadMe(ByVal productCode As String) As String

        Dim readMeText As String = ""

        Dim request As HttpWebRequest = CType(WebRequest.Create(String.Format(READ_ME_URL, productCode)), _
                                                  HttpWebRequest)
        request.KeepAlive = False

        Dim response As HttpWebResponse = CType(request.GetResponse(), _
                                                HttpWebResponse)

        Dim receiveStream As Stream = response.GetResponseStream()
        Dim readStream As New StreamReader(receiveStream, _
                                           Encoding.UTF8)

        Dim pageContents As String = readStream.ReadToEnd

        readStream.Close()
        response.Close()

        Return pageContents

    End Function

    Protected Overrides Sub DownLoadPage(ByVal itemId As Integer)

        Try

            Dim pageContents As String = GetPageContents(itemId)
            Dim requiredProducts As String = ""
            Dim productName As String = ""
            Dim price As Single = 0.0
            Dim artists As String = ""

            Dim productCodeStart As Integer = pageContents.IndexOf(PRICE_START_MATCH)

            If productCodeStart > -1 Then

                requiredProducts = GetRequiredProducts(pageContents)
                price = GetPrice(pageContents)
                productName = GetProductName(pageContents)
                artists = GetArtists(pageContents)

                'pageContents = pageContents.Substring(productCodeStart)
                'pageContents = pageContents.Substring(0, pageContents.IndexOf(PRODUCT_CODE_END_MATCH))
                'pageContents = pageContents.Replace(PRODUCT_CODE_START_MATCH, EMPTY)
                'pageContents = pageContents.Trim

                _linkFile.AddLink(itemId.ToString, _
                                  String.Format(BASE_PAGE_URL, itemId.ToString), _
                                  itemId, _
                                  requiredProducts, _
                                  productName, _
                                  price)

            End If

        Catch ex As System.Net.WebException
            Throw
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

    Public Overrides Sub Download()

        Try

            Dim MinRenderosityId As Integer = _linkFile.MaxId + 1

            Download(MinRenderosityId, _
                     My.Settings.MaxRenderosityId)

            'Download(57124, 57124)

        Catch ex As Exception

        End Try
        _linkFile.WriteFile(LINK_FILENAME)
        'Download(My.Settings.MaxRenderosityId)

    End Sub

End Class
